using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Text;
using Microsoft.XLANGs.BaseTypes;
using System.Globalization;
using System.Resources;
using System.Threading;
namespace BTSProjectWizard.Forms
{
    public class CorrelationPickerPage : BTSProjectWizard.BTSWizardPage
    {
        private System.Windows.Forms.Button _add;
        private System.Windows.Forms.Button _remove;
        private System.Windows.Forms.TreeView _propertiesTree;
        private System.Windows.Forms.ListBox _propertiesList;
        private System.Windows.Forms.Button _addAsms;
        private System.Windows.Forms.OpenFileDialog _assemblyOpen;
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;
        
        public override bool ProcessSymbols()
        {
            bool valid = false;
            if (_propertiesList.Items.Count == 0)
            {
                MessageBox.Show(_rm.GetString("CorrelationError", Thread.CurrentThread.CurrentCulture));
                return valid;
            }
            else
                valid = true;
            MemoryStream ms = new MemoryStream();
            XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.Default);
            //wizard.Add("dummyxml","<s:doc xmlns:s='http://Schema1'></s:doc>");
            tw.WriteStartDocument();
            tw.WriteStartElement("doc");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < _propertiesList.Items.Count; i++)
            {
                tw.WriteStartElement("ctypeproperty");
                tw.WriteElementString("id", Guid.NewGuid().ToString());
                tw.WriteElementString("propertyref", "PropertyRef_" + (i + 1).ToString());
                tw.WriteElementString("type", _propertiesList.Items[i].ToString());
                  tw.WriteEndElement();//var

            }

                tw.WriteEndElement();
            tw.WriteEndDocument();
            tw.Flush();
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            StreamReader sr = new StreamReader(ms);
            string xml = sr.ReadToEnd();
            wizard.AddSymbol("dummyxml", xml);
            sr.Close(); tw.Close(); ms.Close();
            return valid;
        }

        public CorrelationPickerPage()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();
            AddViaLoad("Microsoft.BizTalk.GlobalPropertySchemas, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

        }
        void AddViaLoad(string asmname)
        {
            Assembly a = Assembly.Load(asmname);
            AddAndLoad(a);

        }
        void AddViaLoadFrom(string asmname)
        {
            Assembly a = Assembly.LoadFrom(asmname);
            AddAndLoad(a);
        }
        void AddAndLoad(Assembly asm)
        {
            _assemblies.Add(asm);
            LoadTreeWithNewAssembly(asm);
        }
        void LoadTreeWithNewAssembly(Assembly asm)
        {
            Type[] types = asm.GetTypes();
            Type t = null;
            ArrayList al = null;
            for (int i = 0; i < types.Length; i++)
            {
                t = types[i];
                if (t.BaseType == typeof(MessageContextPropertyBase) || t.BaseType == typeof(MessageDataPropertyBase))
                {
                    if (!_namespaces.ContainsKey(t.Namespace))
                    {
                        _namespaces.Add(t.Namespace, new ArrayList());

                    }
                    al = (ArrayList)_namespaces[t.Namespace];
                    al.Add(t);
                }

            }
            LoadTree();


        }
        void LoadTree()
        {
            _propertiesTree.Nodes.Clear();
            IDictionaryEnumerator de = _namespaces.GetEnumerator();
            ArrayList types = null;
            Type t = null;
            TreeNode tn = null;
            while (de.MoveNext())
            {
                tn = new TreeNode(de.Key.ToString());
                _propertiesTree.Nodes.Add(tn);
                types = (ArrayList)de.Value;
                for (int i = 0; i < types.Count; i++)
                {
                    t = (Type)types[i];
                    tn.Nodes.Add(t.Name);

                }


            }

        }
        Hashtable _namespaces = new Hashtable();

        ArrayList _assemblies = new ArrayList();
        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code
        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CorrelationPickerPage));
            this._propertiesTree = new System.Windows.Forms.TreeView();
            this._propertiesList = new System.Windows.Forms.ListBox();
            this._add = new System.Windows.Forms.Button();
            this._remove = new System.Windows.Forms.Button();
            this._addAsms = new System.Windows.Forms.Button();
            this._assemblyOpen = new System.Windows.Forms.OpenFileDialog();
            this.SuspendLayout();
            // 
            // _propertiesTree
            // 
            resources.ApplyResources(this._propertiesTree, "_propertiesTree");
            this._propertiesTree.ItemHeight = 18;
            this._propertiesTree.Name = "_propertiesTree";
            // 
            // _propertiesList
            // 
            resources.ApplyResources(this._propertiesList, "_propertiesList");
            this._propertiesList.Name = "_propertiesList";
            // 
            // _add
            // 
            resources.ApplyResources(this._add, "_add");
            this._add.Name = "_add";
            this._add.Click += new System.EventHandler(this._add_Click);
            // 
            // _remove
            // 
            resources.ApplyResources(this._remove, "_remove");
            this._remove.Name = "_remove";
            this._remove.Click += new System.EventHandler(this._remove_Click);
            // 
            // _addAsms
            // 
            resources.ApplyResources(this._addAsms, "_addAsms");
            this._addAsms.Name = "_addAsms";
            this._addAsms.Click += new System.EventHandler(this.button1_Click);
            // 
            // _assemblyOpen
            // 
            resources.ApplyResources(this._assemblyOpen, "_assemblyOpen");
            // 
            // CorrelationPickerPage
            // 
            this.Controls.Add(this._addAsms);
            this.Controls.Add(this._remove);
            this.Controls.Add(this._add);
            this.Controls.Add(this._propertiesList);
            this.Controls.Add(this._propertiesTree);
            this.Name = "CorrelationPickerPage";
            resources.ApplyResources(this, "$this");
            this.Leave += new System.EventHandler(this.CorrelationPickerPage_Leave);
            this.ResumeLayout(false);

        }
        #endregion

        private void _add_Click(object sender, System.EventArgs e)
        {
            TreeNode tn = _propertiesTree.SelectedNode;
            if (tn.Parent != null)
            {
                _propertiesList.Items.Add(tn.Parent.Text + "." + tn.Text);
            }
        }

        private void _remove_Click(object sender, System.EventArgs e)
        {
            if (_propertiesList.SelectedIndex != -1)
            {
                _propertiesList.Items.RemoveAt(_propertiesList.SelectedIndex);
            }
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            _assemblyOpen.ShowDialog(this);
            AddViaLoadFrom(_assemblyOpen.FileName);
        }

        private void CorrelationPickerPage_Leave(object sender, EventArgs e)
        {
            StringBuilder sb2 = new StringBuilder();
            for (int i = 0; i < _propertiesList.Items.Count; i++)
            {
                   sb2.AppendFormat("{0}|", _propertiesList.Items[i].ToString());
                

            }

            //
            string p = sb2.ToString();
            if (!String.IsNullOrEmpty(p))
            {
                wizard.AddSymbol("PropertiesPicked", p.Remove(p.Length - 1, 1));
            }

        }
    }
}



